/*
 * @Author: wuzhen
 * @Date: 2019-01-22 09:08:44
 * @LastEditors  : wuzhen
 * @LastEditTime : 2020-01-04 10:07:00
 * @Description: 用户信息
 */
import { login, getUserInfo, LoginOut } from "@/request/api";
import { getToken, removeToken, removeParentrouter } from "@/config/auth";

const user = {
  state: {
    token: getToken(),
    userInfo: {},
    modules: [],
    actions: [],
    menus: [],
    routerMenus: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USERINFO: (state, data) => {
      state.userInfo = data;
    },
    SET_MODULES: (state, data) => {
      state.modules = data;
    },
    SET_ACTIONS: (state, data) => {
      state.actions = data;
    },
    SET_MENUS: (state, data) => {
      state.menus = data;
    },
    SET_ROUTER_MENUS: (state, data) => {
      state.routerMenus = data;
    }
  },
  actions: {
    // 用户名登录
    async onLogin({ commit }, userInfo) {
      const account = userInfo.account.trim();
      return new Promise(async (resolve, reject) => {
        try {
          const res = await login({
            account: account,
            password: userInfo.password
          });
          if (res.code === 200) {
            // 请求成功
            commit("SET_TOKEN", res.attach.sid);
          }
          resolve(res);
        } catch (error) {
          reject(error);
        }
      });
    },
    // 获取用户信息
    async getUserInfoData({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await getUserInfo();
          // 请求成功
          // if (res.code === 200) {

          // }
          commit("SET_USERINFO", res.system_memberinfo);
          commit("SET_MODULES", res.system_rmodules);
          commit("SET_MENUS", res.system_sysmenus);
          commit("SET_ACTIONS", res.system_actiones);
          // 序列化菜单获取路由菜单
          commit("SET_ROUTER_MENUS", fetchAsyncRoutes(res.system_sysmenus));
          resolve(res);
        } catch (error) {
          reject(error);
        }
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise(resolve => {
        LoginOut().then(() => {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          commit("SET_USERINFO", {});
          removeToken();
          removeParentrouter();
          resolve();
        });
      });
    }
  }
};

// 序列化菜单
function fetchAsyncRoutes(routes) {
  let res = [];
  routes.forEach(v => {
    const tmp = { ...v };
    res.push(tmp);
    if (tmp.children) {
      res = [...res, ...fetchAsyncRoutes(tmp.children)];
    }
  });
  return res;
}

export default user;
